<template>
  <el-form
    :model="searchForm"
    :inline="inline"
    :label-width="labelWidth"
    class="search-form"
    @submit.prevent
  >
    <!-- 动态渲染搜索字段 -->
    <el-form-item
      v-for="(item, index) in fields"
      :key="index"
      :label="item.label"
      :prop="item.prop"
    >
      <!-- 输入框 -->
      <el-input
        v-if="item.type === 'input'"
        v-model="searchForm[item.prop]"
        :placeholder="item.placeholder || `请输入${item.label}`"
        :clearable="item.clearable !== false"
        :disabled="item.disabled"
        :style="item.style"
        :maxlength="item.maxlength"
        @keyup.enter.native="handleSearch"
      />

      <!-- 选择器 -->
      <el-select
        v-else-if="item.type === 'select'"
        v-model="searchForm[item.prop]"
        :placeholder="item.placeholder || `请选择${item.label}`"
        :clearable="item.clearable !== false"
        :disabled="item.disabled"
        :style="item.style"
        :multiple="item.multiple || false"
        :filterable="item.filterable || false"
      >
        <el-option
          v-for="option in item.options"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>

      <!-- 日期选择器 -->
      <el-date-picker
        v-else-if="item.type === 'date'"
        v-model="searchForm[item.prop]"
        :placeholder="item.placeholder || `请选择${item.label}`"
        :clearable="item.clearable !== false"
        :disabled="item.disabled"
        :style="item.style"
        type="date"
        value-format="YYYY-MM-DD"
      />

      <!-- 日期范围选择器 -->
      <el-date-picker
        v-else-if="item.type === 'date-range'"
        v-model="searchForm[item.prop]"
        :placeholder="item.placeholder || ['开始日期', '结束日期']"
        :clearable="item.clearable !== false"
        :disabled="item.disabled"
        :style="item.style"
        type="daterange"
        value-format="YYYY-MM-DD"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      />

      <!-- 日期时间选择器 -->
      <el-date-picker
        v-else-if="item.type === 'datetime'"
        v-model="searchForm[item.prop]"
        :placeholder="item.placeholder || `请选择${item.label}`"
        :clearable="item.clearable !== false"
        :disabled="item.disabled"
        :style="item.style"
        type="datetime"
        value-format="YYYY-MM-DD HH:mm:ss"
      />

      <!-- 日期时间范围选择器 -->
      <el-date-picker
        v-else-if="item.type === 'datetime-range'"
        v-model="searchForm[item.prop]"
        :placeholder="item.placeholder || ['开始时间', '结束时间']"
        :clearable="item.clearable !== false"
        :disabled="item.disabled"
        :style="item.style"
        type="datetimerange"
        value-format="YYYY-MM-DD HH:mm:ss"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
      />

      <!-- 单选框组 -->
      <el-radio-group v-else-if="item.type === 'radio'" v-model="searchForm[item.prop]">
        <el-radio
          v-for="option in item.options"
          :key="option.value"
          :label="option.value"
        >
          {{ option.label }}
        </el-radio>
      </el-radio-group>

      <!-- 多选框组 -->
      <el-checkbox-group v-else-if="item.type === 'checkbox'" v-model="searchForm[item.prop]">
        <el-checkbox
          v-for="option in item.options"
          :key="option.value"
          :label="option.value"
          style="margin-right: 15px;"
        >
          {{ option.label }}
        </el-checkbox>
      </el-checkbox-group>

      <!-- 自定义组件 -->
      <slot v-else-if="item.type === 'custom'" :name="item.prop"></slot>
    </el-form-item>

    <!-- 操作按钮 -->
    <el-form-item class="search-form-actions">
      <el-button type="primary" @click="handleSearch" :loading="loading">
        <el-icon><Search /></el-icon>
        搜索
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
      <slot name="actions"></slot>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'

// 定义组件的props
const props = defineProps({
  // 搜索字段配置
  fields: {
    type: Array,
    required: true,
    default: () => []
  },
  // 初始搜索值
  initialValues: {
    type: Object,
    default: () => {}
  },
  // 是否内联表单
  inline: {
    type: Boolean,
    default: true
  },
  // 标签宽度
  labelWidth: {
    type: String,
    default: '80px'
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
})

// 定义事件
const emit = defineEmits(['search', 'reset'])

// 搜索表单数据
const searchForm = reactive({})

// 初始化搜索表单
function initSearchForm() {
  // 重置表单
  Object.keys(searchForm).forEach(key => {
    delete searchForm[key]
  })

  // 设置初始值
  props.fields.forEach(field => {
    // 设置默认值
    if ('defaultValue' in field) {
      searchForm[field.prop] = field.defaultValue
    } else {
      // 根据字段类型设置默认值
      if (field.type === 'checkbox' || field.type === 'select' && field.multiple) {
        searchForm[field.prop] = []
      } else if (field.type === 'date-range' || field.type === 'datetime-range') {
        searchForm[field.prop] = []
      } else {
        searchForm[field.prop] = ''
      }
    }

    // 如果有初始值，覆盖默认值
    if (props.initialValues && field.prop in props.initialValues) {
      searchForm[field.prop] = props.initialValues[field.prop]
    }
  })
}

// 处理搜索
function handleSearch() {
  // 构建搜索参数
  const searchParams = {}
  props.fields.forEach(field => {
    const value = searchForm[field.prop]
    // 过滤掉空值
    if (value !== '' && value !== null && value !== undefined) {
      searchParams[field.prop] = value
    }
  })
  
  emit('search', searchParams)
}

// 处理重置
function handleReset() {
  initSearchForm()
  emit('reset')
}

// 监听fields变化，重新初始化表单
import { watch } from 'vue'
watch(() => props.fields, () => {
  initSearchForm()
}, { deep: true, immediate: true })

// 监听initialValues变化，更新表单
watch(() => props.initialValues, (newValues) => {
  if (newValues) {
    Object.keys(newValues).forEach(key => {
      if (key in searchForm) {
        searchForm[key] = newValues[key]
      }
    })
  }
}, { deep: true })

// 暴露方法给父组件
defineExpose({
  handleSearch,
  handleReset,
  searchForm
})
</script>

<style scoped>
.search-form {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.search-form-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-date-editor),
:deep(.el-input),
:deep(.el-select) {
  width: 180px;
}

:deep(.el-radio) {
  margin-right: 15px;
}

@media screen and (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 12px;
    width: 100%;
  }
  
  :deep(.el-date-editor),
  :deep(.el-input),
  :deep(.el-select) {
    width: 100%;
  }
}
</style>